package ru.spb.osll.myfit.client.view;

import com.google.gwt.user.client.ui.Widget;
import ru.spb.osll.myfit.client.Mode;
import ru.spb.osll.myfit.client.event.PageButtonEvent;
import ru.spb.osll.myfit.client.event.TagAddEvent;
import ru.spb.osll.myfit.client.widget.PageButtonEventListener;
import ru.spb.osll.myfit.client.widget.SuiteWidget;
import ru.spb.osll.myfit.common.Suite;

public class SuiteView extends AbstractView {
  private String m_id;
  private SuiteWidget m_suiteWidget;
  private PageButtonEventListener m_buttonEventListener;
  private SuiteToolBar m_toolBar;

  private PageButtonEventListener createButtonEventListener(final PageButtonEventListener pageButtonEventListener) {
    return new PageButtonEventListener() {
      @Override
      public void actionPerformed(PageButtonEvent event) {
        switch (event.getType()) {
          case TO_EDIT_MODE:
            changeMode(Mode.EDIT);
            break;
          case TO_VIEW_MODE:
            changeMode(Mode.VIEW);
            break;
          case ADD_TAG:
            if (event instanceof TagAddEvent) {
              ((TagAddEvent) event).setAlreadyExists(!m_suiteWidget.addTag(((TagAddEvent) event).getTagName()));
            }
            break;
          default:
            pageButtonEventListener.actionPerformed(event);
            break;
        }
      }
    };
  }

  public SuiteView(String id, PageButtonEventListener pageButtonEventListener) {
    m_id = id;
    m_buttonEventListener = createButtonEventListener(pageButtonEventListener);

    createRootPanel();
  }

  @Override
  protected Widget createContentPanel() {
    m_suiteWidget = new SuiteWidget();
    return m_suiteWidget;
  }

  @Override
  protected Widget createEditPanel() {
    m_toolBar = new SuiteToolBar(m_buttonEventListener, m_id);
    return m_toolBar;
  }

  public void displaySuite(Suite suite) {
    m_suiteWidget.setSuite(suite);
  }

  public Suite getSuite() {
    return m_suiteWidget.getSuite();
  }

  private void changeMode(Mode newMode){
    m_suiteWidget.setMode(newMode);
    m_toolBar.setMode(newMode);
  }
}
